import config from '../../../../config/config.js'
import LayoutObserver from './../unit/layout-observer'
import {getCell, getColumnByCell} from "../unit/util"

export default {
  name: config.prefix + '-table-footer',

  mixins: [LayoutObserver],

  render (h) {
    let summaryData = []
    if (this.summaryMethod) {
      summaryData = this.summaryMethod({
        columns: this.columns,
        data: this.store.states.data
      })
    } else {
      this.columns.forEach((column, index) => {
        if (index === 0 && this.fixed !== 'right') {
          summaryData[index] = this.sumText
          return
        }
        const values = this.store.states.data.map(item => Number(item[column.property]))
        const precisions = []
        let notNumber = true
        values.forEach(value => {
          if (!isNaN(value)) {
            notNumber = false
            const decimal = ('' + value).split('.')[1]
            precisions.push(decimal ? decimal.length : 0)
          }
        })
        const precision = Math.max.apply(null, precisions)
        if (!notNumber) {
          summaryData[index] = values.reduce((prev, curr) => {
            const value = Number(curr)
            if (!isNaN(value)) {
              return parseFloat((prev + curr).toFixed(Math.min(precision, 20)))
            } else {
              return prev
            }
          }, 0)
        } else {
          summaryData[index] = ''
        }
      })
    }
    return (
      <table
        class="aty-table__footer"
        cellspacing="0"
        cellpadding="0"
        border="0">
        <colgroup>
          {
            this._l(this.columns, column => <col name={column.id}/>)
          }
          {
            this.hasGutter ? <col name="gutter"/> : ''
          }
        </colgroup>
        <tbody class={[{ 'has-gutter': this.hasGutter }]}>
          <tr on-click={($event) => this.handleClick($event, summaryData)}>
            {
              this._l(this.columns, (column, cellIndex) =>
                <td
                  colspan={column.colSpan}
                  class={[column.id, column.headerAlign, column.className || '', !column.children ? 'is-leaf' : '', column.labelClassName]}>
                  <div class={['cell', column.labelClassName]}>{ summaryData[cellIndex] }</div>
                </td>
              )
            }
            {
              this.hasGutter ? <th class="gutter"></th> : ''
            }
          </tr>
        </tbody>
      </table>
    )
  },

  props: {
    fixed: String,
    store: {
      required: true
    },
    summaryMethod: Function,
    sumText: String,
    border: Boolean
  },

  computed: {
    table () {
      return this.$parent
    },

    columnsCount () {
      return this.store.states.columns.length
    },

    columns () {
      if (this.fixed === 'left') {
        return this.store.states.fixedColumns;
      } else if (this.fixed === 'right') {
        return this.store.states.rightFixedColumns;
      }
      return this.store.states.columns;
    },

    hasGutter () {
      return !this.fixed && this.tableLayout.gutterWidth
    }
  },

  methods: {

    handleClick(event, summaryData) {
      /**
       * #event
       *
       * @name    summary-click
       * @param   summaryData
       * @param   column
       * @param   cell
       * @param   event
       * @body
       * @description 当尾行合计的某一列被点击时会触发该事件
       */
      const cell = getCell(event);
      const column = getColumnByCell(this.table, cell);
      if (column) {
        this.table.$emit('summary-click', summaryData, column, cell, event);
      }
    }

  }
}
